﻿
var isEmpty = function (obj) {
    if (obj == null) {
        return true;
    }
    if (typeof (obj) == 'string' && jQuery.trim(obj) == '') {
        return true;
    }
    if (typeof (obj) == 'object') {
        return jQuery.isEmptyObject(obj);
    }
    return false;
};
var isNotEmpty = function (obj) {
    return !isEmpty(obj);
};


var DateContUtil2 = function (obj) { this.init.apply(this, [obj]); };
DateContUtil2.prototype = {
    init: function (obj) {
        this.title = obj.title ? obj.title : '日期';
        this.selectId = obj.selectId ? obj.selectId : "";
        this.defaultValue = obj.defaultValue ? obj.defaultValue : "0";
        this.startDate = obj.startDate ? obj.startDate : "search_startDateBase";
        this.endDate = obj.endDate ? obj.endDate : "search_endDateBase";
        this.selectedFun = obj.selectedFun ? obj.selectedFun : null;
        this.removeOption = obj.removeOption ? obj.removeOption : "";
        this.cloneArray = obj.cloneArray ? obj.cloneArray : [];
        this.createDom();
    },
    createDom: function () {
        var select = $('#' + this.selectId);
        select.append($("<option>").val('0').text('日期'));
        select.append($("<option>").val('1').text('今日'));
        select.append($("<option>").val('2').text('昨日'));
        select.append($("<option>").val('3').text('本周'));
        select.append($("<option>").val('7').text('上月'));
        select.append($("<option>").val('4').text('本月'));
        select.append($("<option>").val('5').text('本季'));
        select.append($("<option>").val('6').text('本年'));
        select.val(this.defaultValue);

        if (isNotEmpty(this.removeOption)) {
            var arr = this.removeOption.split(',');
            for (var i = 0; i < arr.length; i++) {
                select.find("option[value='" + arr[i] + "']").remove();
            }
        }

        var _this = this;
        $('#' + this.selectId).change(function () {

            var val = $("#" + _this.selectId + "  option:selected").val();
            _this.putSelect(val);
            if (_this.selectedFun != null) {
                _this.selectedFun.call(_this);
            }
        });

        $('#' + this.startDate).click(function () {
            select.val('0');
        });

        $('#' + this.endDate).click(function () {
            select.val('0');
        });

        _this.putSelect(_this.defaultValue);

    },
    putSelect: function (val) {
        var beginId = this.startDate;
        var endId = this.endDate;
        if (val == '0') {
            $('#' + beginId).val('');
            $('#' + endId).val('');
        } else if (val == '1') {
            var date = CommonUtil.getNowDate;
            $('#' + beginId).val(date);
            $('#' + endId).val(date);
        } else if (val == '2') {
            var date = CommonUtil.getYesterday;
            $('#' + beginId).val(date);
            $('#' + endId).val(date);
        } else if (val == '3') {
            $('#' + beginId).val(CommonUtil.getWeekStartDate);
            $('#' + endId).val(CommonUtil.getWeekEndDate);
        } else if (val == '4') {
            $('#' + beginId).val(CommonUtil.getMonthStartDate);
            $('#' + endId).val(CommonUtil.getMonthEndDate);
        } else if (val == '5') {
            $('#' + beginId).val(CommonUtil.getQuarterStartDate);
            $('#' + endId).val(CommonUtil.getQuarterEndDate);
        } else if (val == '6') {
            $('#' + beginId).val(CommonUtil.getYearStartDate);
            $('#' + endId).val(CommonUtil.getYearEndDate);
        } else if (val == '7') {
            $('#' + beginId).val(CommonUtil.getLastMonthStartDate);
            $('#' + endId).val(CommonUtil.getLastMonthEndDate);
        }

        var cloneArray = this.cloneArray;
        if ($.isArray(cloneArray)) {
            for (var i = 0; i < cloneArray.length; i++) {
                var arr = cloneArray[i].split(',');
                if (arr.length > 1) {
                    $('#' + arr[0]).val($('#' + beginId).val());
                    $('#' + arr[1]).val($('#' + endId).val());
                }
            }
        }
    }
};




var CommonUtil = {};

/*将String类型解析为Date类型.       
  parseDate('2006-1-1') return new Date(2006,0,1)       
  parseDate(' 2006-1-1 ') return new Date(2006,0,1)       
  parseDate('2006-1-1 15:14:16') return new Date(2006,0,1,15,14,16)       
  parseDate(' 2006-1-1 15:14:16 ') return new Date(2006,0,1,15,14,16);       
  parseDate('2006-1-1 15:14:16.254') return new Date(2006,0,1,15,14,16,254)       
  parseDate(' 2006-1-1 15:14:16.254 ') return new Date(2006,0,1,15,14,16,254)       
  parseDate('不正确的格式') retrun null       
 */
CommonUtil.parseDate = function (str) {
    if (typeof str == 'string') {
        var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);
        if (results && results.length > 3)
            return new Date(Number(results[1]), Number(results[2]) - 1, Number(results[3]));
        results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
        if (results && results.length > 6)
            return new Date(Number(results[1]), Number(results[2]) - 1, Number(results[3]), Number(results[4]), Number(results[5]), Number(results[6]));
        results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);
        if (results && results.length > 7)
            return new Date(Number(results[1]), Number(results[2]) - 1, Number(results[3]), Number(results[4]), Number(results[5]), Number(results[6]), Number(results[7]));
    }
    return null;
};

/*       
  将Date/String类型,解析为String类型.       
  传入String类型,则先解析为Date类型       
  不正确的Date,返回 ''       
  如果时间部分为0,则忽略,只返回日期部分.       
 */
CommonUtil.formatDate = function (v, dateFormat) {
    if (typeof v == 'string') v = parseDate(v);
    if (v instanceof Date) {
        var y = v.getFullYear();
        var m = v.getMonth() + 1;
        var d = v.getDate();
        var h = v.getHours();
        var i = v.getMinutes();
        var s = v.getSeconds();
        var ms = v.getMilliseconds();
        if (dateFormat != null && dateFormat != "" && dateFormat == "yyyy-MM-dd") return y + '-' + m + '-' + d;
        //		if(ms>0) return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s + '.' + ms;          
        if (h > 0 || i > 0 || s > 0) return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
        return y + '-' + m + '-' + d;
    }
    return '';
};

CommonUtil.formatDateRenderer = function (v, dateFormat) {
    if (isEmpty(v)) return "";
    if (dateFormat != "Y-m-d") dateFormat = 'Y-m-d';
    var d = null;
    if (v.length > 10) {
        d = Date.parseDate(v, "Y-m-d h:i:s").format(dateFormat);
    } else {
        d = Date.parseDate(v, "Y-m-d").format(dateFormat);
    }
    return d;
};
/**
 * 返回format后的字符串时间类型
 * @param v
 * @param dateFormat
 * @returns
 */
CommonUtil.formatDateRendererTime = function (v, dateFormat) {
    if (isEmpty(v)) return "";
    if (v.length >= 19) v = v.substr(0, 19);
    if (dateFormat != "Y-m-d") dateFormat = 'Y-m-d h:i:s';
    var d = null;
    if (v.length > 10) {
        d = Date.parseDate(v, "Y-m-d h:i:s").format(dateFormat);
    } else {
        d = Date.parseDate(v, "Y-m-d").format(dateFormat);
    }
    return d;
};
/**
 * 返回format后的时间类型
 * @param v
 * @param dateFormat
 * @returns
 */
CommonUtil.dateRendererTime = function (v, dateFormat) {
    if (isEmpty(v)) return "";
    if (v.length >= 19) v = v.substr(0, 19);
    if (dateFormat != "Y-m-d") dateFormat = 'Y-m-d h:i:s';
    var d = null;
    if (v.length > 10) {
        d = Date.parseDate(v, "Y-m-d h:i:s");
    } else {
        d = Date.parseDate(v, "Y-m-d");
    }
    return d;
};

CommonUtil.formatDateToYMD = function (cellvalue, options, rowObject) {
    if (isEmpty(cellvalue)) return "";
    var d = formatDateRendererTime(cellvalue, "Y-m-d");
    return d;
};
CommonUtil.formatDateToYMDHIS = function (cellvalue, options, rowObject) {
    if (isEmpty(cellvalue)) return "";
    var d = CommonUtil.formatDate(cellvalue, "Y-m-d h:i:s");
    return d;
};

/*******************************日期yyyy-MM-dd***********************************/
var now = new Date();                    //当前日期     
var nowDayOfWeek = now.getDay();         //今天本周的第几天     
var nowDay = now.getDate();              //当前日     
var nowMonth = now.getMonth();           //当前月     
var nowYear = now.getYear();             //当前年     
nowYear += (nowYear < 2000) ? 1900 : 0;  // 

CommonUtil.lastMonthDate = new Date();  //上月日期  
CommonUtil.lastMonthDate.setDate(1);
CommonUtil.lastMonthDate.setMonth(CommonUtil.lastMonthDate.getMonth() - 1);
CommonUtil.lastYear = CommonUtil.lastMonthDate.getYear();
CommonUtil.lastMonth = CommonUtil.lastMonthDate.getMonth();

//格式化日期：yyyy-MM-dd     
function formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;
    var myweekday = date.getDate();

    if (mymonth < 10) {
        mymonth = "0" + mymonth;
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday;
    }
    return (myyear + "-" + mymonth + "-" + myweekday);
}
function formatDateYM(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;

    if (mymonth < 10) {
        mymonth = "0" + mymonth;
    }
    return (myyear + "-" + mymonth);
}
//获得某月的天数     
function getMonthDays(myMonth) {
    var monthStartDate = new Date(nowYear, myMonth, 1);
    var monthEndDate = new Date(nowYear, myMonth + 1, 1);
    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
    return days;
}
//获得本季度的开始月份     
function getQuarterStartMonth() {
    var quarterStartMonth = 0;
    if (nowMonth < 3) {
        quarterStartMonth = 0;
    }
    if (2 < nowMonth && nowMonth < 6) {
        quarterStartMonth = 3;
    }
    if (5 < nowMonth && nowMonth < 9) {
        quarterStartMonth = 6;
    }
    if (nowMonth > 8) {
        quarterStartMonth = 9;
    }
    return quarterStartMonth;
}
//【今天(带时分秒)】       
CommonUtil.getNowDateTime = function () {
    var v = new Date();
    return CommonUtil.formatDate(v, 'yyyy-MM-dd hh:mm:ss');
};
//【今天】       
CommonUtil.getNowDate = function () {
    var v = new Date();
    return formatDate(v);
};
//【昨天】
CommonUtil.getYesterday = function () {
    var v = new Date(new Date() - 1000 * 60 * 60 * 24);
    return formatDate(v);
};
//【本周】の开始日期
CommonUtil.getWeekStartDate = function () {
    var v = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
    return formatDate(v);
};
//【上个月】の日期
CommonUtil.getLastMonthDate = function () {
    var year = nowYear;
    var month = nowMonth;
    if (month == 1) {
        year = year - 1;
        month = 12;
    } else {
        month = month - 1;
    }
    var v = new Date(year, month, nowDay);
    return formatDate(v);
};
//【本周】の结束日期
CommonUtil.getWeekEndDate = function () {
    var v = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
    return formatDate(v);
};
//【上月】の开始时间  
CommonUtil.getLastMonthStartDate = function () {
    //    var lastMonthStartDate = new Date(nowYear, CommonUtil.lastMonth, 1); 
    var year = nowYear;
    var month = nowMonth;
    if (month == 1) {
        year = year - 1;
        month = 12;
    } else {
        month = month - 1;
    }
    var lastMonthStartDate = new Date(year, month, 1);
    return formatDate(lastMonthStartDate);
};

//【上月】の结束时间  
CommonUtil.getLastMonthEndDate = function () {
    //    var lastMonthEndDate = new Date(nowYear, CommonUtil.lastMonth, getMonthDays(CommonUtil.lastMonth));  
    var year = nowYear;
    var month = nowMonth;
    if (month == 1) {
        year = year - 1;
        month = 12;
    } else {
        month = month - 1;
    }
    var lastMonthEndDate = new Date(year, month, getMonthDays(CommonUtil.lastMonth));
    return formatDate(lastMonthEndDate);
};
//【本月】の开始日期
CommonUtil.getMonthStartDate = function () {
    var v = new Date(nowYear, nowMonth, 1);
    return formatDate(v);
};
//【本月】の结束日期
CommonUtil.getMonthEndDate = function () {
    var v = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
    return formatDate(v);
};
//【本季】の开始日期
CommonUtil.getQuarterStartDate = function () {
    var v = new Date(nowYear, getQuarterStartMonth(), 1);
    return formatDate(v);
};
//【本季】の结束日期
CommonUtil.getQuarterEndDate = function () {
    var m = getQuarterStartMonth() + 2;
    var v = new Date(nowYear, m, getMonthDays(m));
    return formatDate(v);
};
//【本年】の开始日期
CommonUtil.getYearStartDate = function () {
    var v = new Date(nowYear, 0, 1);
    return formatDate(v);
};
//【本年】の结束日期
CommonUtil.getYearEndDate = function () {
    var v = new Date(nowYear, 11, 31);
    return formatDate(v);
};


/*******************************日期yyyy-MM-dd***********************************/

//保留2位小数
CommonUtil.formatMoney = function (cellvalue, options, rowObject) {
    if (isEmpty(cellvalue)) {
        return "";
    }
    value = CommonUtil.fmoney(cellvalue, 2);
    return value;
};

//格式化金额    
CommonUtil.fmoney = function (s, n) {//将数字转换成逗号分隔的样式,保留两位小数s:value,n:小数位数      
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
};
CommonUtil.onlyFloat = function (id, n) {
    if (isEmpty(n)) {
        try {
            n = top.appOrgInfo.kcSlDecimal;//【系统参数】数量小数位数(0至4)
        } catch (e) { n = 2; }
    }
    var fix = '{0,' + n + '}';
    $("#" + id).keyup(function () {
        FormUtil.onlyFloat({
            id: id,
            fix: fix
        });
    });
};
//【数量】格式化   ,默认2位 ，（由系统参数控制多少位）
CommonUtil.fmoneyToNum = function (s) {//将数字转换成保留两位小数s:value,n:小数位数      
    var n = 2;//由【系统参数】控制保留多少位,现在默认2位
    try {
        n = top.appOrgInfo.kcSlDecimal;//【系统参数】数量小数位数(0至4)
    } catch (e) {
        n = 2;
    }
    s = CommonUtil.scNum(s);
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
    }
    return t.split("").reverse().join("") + "." + r;
};
//格式化金额   ,默认2位 
CommonUtil.fmoneyToc = function (s, n) {//将数字转换成保留两位小数s:value,n:小数位数      
    n = n > 0 && n <= 20 ? n : 2;
    s = CommonUtil.scNum(s);
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
    }
    return t.split("").reverse().join("") + "." + r;
};

//2数相加
CommonUtil.accAdd = function (arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
};
//2数相除
CommonUtil.accDiv = function (arg1, arg2) {
    if (isEmpty(arg1)) arg1 = '0';
    if (isEmpty(arg2)) arg2 = '0';
    var t1 = 0, t2 = 0, r1, r2;
    try { t1 = arg1.toString().split(".")[1].length; } catch (e) { }
    try { t2 = arg2.toString().split(".")[1].length; } catch (e) { }
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * pow(10, t2 - t1);
    }
};
//2数相乘
CommonUtil.accMul = function (arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length; } catch (e) { }
    try { m += s2.split(".")[1].length; } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
};
//还原金额   
CommonUtil.rmoney = function (s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
};

CommonUtil.scNum = function (value) {
    if (isEmpty(value)) return 0;
    var num = 0;
    if ((num = value.indexOf('E')) != -1 || (num = value.indexOf('e')) != -1) {
        var doubleStr = value.substring(0, num);
        var eStr = value.substring(num + 1, value.length);
        eStr = parseInt(eStr);
        var doubleStrList = doubleStr.split('.');
        var doubleStr1 = doubleStrList[0];
        var doubleStr2 = doubleStrList[1];

        if (doubleStr2.length > eStr) {
            var nums = doubleStr2.substring(0, eStr);
            var nume = doubleStr2.substring(eStr, doubleStr2.length);
            doubleStr = doubleStr1 + nums + '.' + nume;
        }
        else if (doubleStr2.length < eStr) {
            var indexNum = eStr - doubleStr2.length;
            //用0补齐
            var str = '';
            for (var i = 0; i < indexNum; i++) {
                str += '0';
            }
            doubleStr = doubleStr1 + doubleStr2 + str;
        } else {
            doubleStr = doubleStr1 + doubleStr2;
        }
        value = doubleStr;
        //千分位
    }
    return value;
};

CommonUtil.byteTofileSize = function (value) {
    if (isEmpty(value)) return '0 B';
    var mb = CommonUtil.accMul(1024, 1024);
    var kb = 1024;
    if (parseFloat(value) > mb) {
        return (parseFloat(value) / mb).toFixed(2) + " MB";
    } else if (parseFloat(value) > kb) {
        return (parseFloat(value) / kb).toFixed(2) + " KB";
    } else {
        return value + " B";
    }
};